package com.hgc.consumerrabbit.controller;

import com.alibaba.fastjson2.JSON;
import com.hgc.consumerrabbit.mapper.producerMapper;
import com.hgc.consumerrabbit.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 生产者
 */

@RestController
public class ProducerController {

    /**
     * Rabbit操作类
     */
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private producerMapper producerMapper;

    @GetMapping("/sendMsgByString")
    public void sendMsgByString(String data,HttpServletRequest request) {

        try {
            /**
             * 参数1 交换机名字
             * 参数2 路由key
             * 参数3 发送的消息
             * 该方法会向 跟交换机绑定的队列发送消息
             */

            amqpTemplate.convertAndSend("EXCHANGES_DEMO","", data);


            /**
             * 记录操作
             */
            String ip = request.getRemoteAddr();
            producerMapper.insert(ip, data, new Date());
        } catch (Exception e) {
            throw e;
        }

    }

    /**
     * 向 RabbitMQ 发送一个 User 对象
     */
    @PostMapping("/sendMsgByObject")
    public void sendMsgByObject(@RequestBody User user, HttpServletRequest request) {

        try {
            /**
             * 参数1 交换机名字
             * 参数2 路由key
             * 参数3 发送的消息
             * 该方法会向 跟交换机绑定的队列发送消息
             */

            amqpTemplate.convertAndSend("EXCHANGES_DEMO","", user);


            /**
             * 记录操作
             */
            String ip = request.getRemoteAddr();
            String data = JSON.toJSONString(user);

            producerMapper.insert(ip, data, new Date());
        } catch (Exception e) {
            throw e;
        }

    }
}
